/**
 * 地址选择插件
 * Author: void rangers
 * Versions: 1.0.2
 * Date: 2021-1-22
 * **/

;
!function(win){
    const HTML = {
        dom: `
            <div class="site_selection">
                <div class="site_map" id="site_map_container"></div>
                <div class="site_platform">
                    <div class="site_search"><input type="text" id="site_search" placeholder="请输入关键词搜索" /></div>
                    <div class="site_title">定位点信息</div>
                    <div class="site_cont">
                        <div class="site_h">经纬度 <i>Coordinate</i></div>
                        <div class="site_c" id="site_coordinate"></div>
                        <div class="site_h">区域 <i>District</i></div>
                        <div class="site_c" id="site_district"></div>
                        <div class="site_h">街道 <i>Street</i></div>
                        <div class="site_c" id="site_street"></div>
                        <div class="site_h">地址 <i>Address</i></div>
                        <div class="site_c" id="site_address"></div>
                    </div>
                    <div class="site_btn_group">
                        <div class="site_btn site_confirm">确认选址</div>
                        <div class="site_btn site_close">关闭</div>
                    </div>
                </div>
            </div>
        `,
        css: `
            <style>
                .site_selection *, .site_selection{ margin: 0; padding: 0; box-sizing: border-box;}
                .site_selection{ width: 80%; max-width: 800px; height: 400px; background-color: #FFF; border-radius: 10px; overflow: hidden; position: fixed; top: 0; left: 0; transform-origin: 0 0; transform: translate(0, 0) scale(0); z-index: 99; box-shadow: 0 0 8px rgb(169 166 166 / 50%); transition:all .5s;}
                .site_selection.show{ top:50% !important; left:50% !important; transform: translate(-50%, -50%) scale(1);}
                .site_selection .site_map{ float: left; width: 500px; height: 100%;}

                .site_selection .site_platform{ width: 100%; height: 100%; padding-left: 500px; padding-top: 15px;}
                .site_platform .site_search{ width: 200px; border: 1px solid #DDD; border-radius: 5px; margin-left: 10px;}
                .site_platform .site_search input{ width: 100%; line-height: 30px; outline: none; border: 0; padding: 0 10px; vertical-align: top;}

                .site_platform .site_title{ line-height: 30px; margin-top: 15px; padding-left: 12px; background-color: #b3b3b3; color: #FFF;}
                .site_platform .site_cont{ padding: 10px 7px; font-size: 15px;}
                .site_platform .site_cont .site_h i{ font-size: 12px; color: #D4D3D3;}
                .site_platform .site_cont .site_c{ height: 30px; line-height: 20px; font-size: 13px; color: #636363; padding: 5px 0 5px 20px;}

                .site_platform .site_btn_group{ position: absolute; right: 15px; bottom: 10px;}
                .site_btn_group .site_btn{ display: inline-block; width: 98px; line-height: 35px; font-size: 15px; background-color: #909399; color: #fff; text-align: center; border-radius: 5px; margin-left: 15px; cursor: pointer;}
                .site_btn_group .site_btn.site_confirm{ background-color: #409eff;}
                .site_btn_group .site_btn:hover{ background-color: #a6a9ad;}
                .site_btn_group .site_btn.site_confirm:hover{ background-color: #66b1ff;}
            </style>
        `
    };

    var Siting = function (options){
        this.default = {
            key: '',            //高德 JSAPI 秘钥
            version: '1.4.15',  //高德版本号
            AMap: null,         //高德AMap对象(仅为兼容script引入, 启用时key和version失效)
            center: '',         //地图中心点，若未填，则自动定位当前位置 (示例：[lng, lat])
            success: function(res){}
        };
        this.html = HTML.dom;
        this.style = HTML.css;
        this.ele = null;    //传入的信息
        this.map = null;
        this.oriAddress = null; //初始位置信息
        this.opt = Object.assign({}, this.default, options);
        document.head.appendChild(this.fragment(this.style));
        document.body.appendChild(this.fragment(this.html));

        if(this.opt.AMap){
            this.init(this.opt.AMap);
            this.AMap = this.opt.AMap;
        } else {
            if(!this.opt.key){
                console.error('Lack key：请先填写秘钥');
                return false;
            }
            
            AMapLoader.load({
                "key": this.opt.key,
                "version": this.opt.version,
                "plugins": ['AMap.Marker', 'AMap.Geolocation', 'AMap.Geocoder', 'AMap.AutoComplete', 'AMap.Autocomplete'],
            }).then(AMap => {
                this.init(AMap);
                this.AMap = AMap;
            }).catch(err => {
                console.error('AMapLoader Error:', err);  //加载错误提示
            });
        }

        return this;
    };

    Siting.prototype = {
        init(AMap){
            let autoComplete = new AMap.Autocomplete({  //搜索提示组件
                city: '全国',
                input: 'site_search'
            });
            this.geocoder = new AMap.Geocoder();
            autoComplete.on('select', (res) => {
                // console.log('select:', res);
                if(!this.map) return false;
                let lnglat = res.poi.location;
                this.result.poi = res.poi;
                if(!lnglat){
                    this.geocoder.getLocation(res.poi.district + res.poi.name, (status, res) => {
                        // console.log('getLocation:', res);
                        if(status === 'complete' && res.info === 'OK') this.map.setCenter(res.geocodes[0].location);
                    });
                }
                this.map.setCenter(lnglat);
            });

            if(this.opt.center){    //逆地理编码
                //跳转到固定位置
                this.mapInit([this.opt.center[0], this.opt.center[1]]);
            } else {
                //定位到当前位置
                let geolocation = new AMap.Geolocation({    //浏览器定位
                    timeout: 10000,
                    zoomToAccuracy: true,
                    buttonPosition: 'RB'
                });
                geolocation.getCurrentPosition((status, res) => {
                    if(status == 'complete'){
                        // console.log('Positioning Success:', res);
                        this.mapInit(res.position);
                    } else {
                        console.error('Positioning Error:', res + (res == 'INVALID_USER_KEY' ? '! 当前Key有误，因不具备权限或已过期！' : ''));
                        return false;
                    }
                });
            }

            document.querySelector('.site_confirm').addEventListener('click', (e) => {
                this.opt.success(this.result, this.ele);
                this.hide();
            });
            document.querySelector('.site_close').addEventListener('click', () => {
                this.hide();
            });
        },
        mapInit(lnglat){
            // console.log('map init:', lnglat);
            this.geocoder.getAddress(lnglat, (status, res) => {
                if(status === 'complete' && res.info === 'OK'){
                    // console.log('getAddress:', res);
                    this.oriAddress = Object.assign({}, res.regeocode, lnglat);
                    this.createData(res.regeocode, lnglat);
                } else {
                    console.error('GetAddress Error:', res + (res == 'INVALID_USER_KEY' ? '! 当前Key有误，因不具备权限或已过期！' : ''));
                    return false;
                }

                this.map = new this.AMap.Map('site_map_container', {
                    center: lnglat,
                    zoom: 15
                });
                this.map.on('complete', (ev) => {
                    this.marker = new this.AMap.Marker({
                        map: this.map,
                        position: lnglat,
                        raiseOnDrag: true
                    });
                    this.getAddress();
                });
            })
        },
        getAddress(){
            this.map.on('mapmove', (e) => {
                let lnglat = this.map.getCenter();
                // console.log('move:', e, lnglat);
                this.marker.setPosition(lnglat);
                this.geocoder.getAddress(lnglat, (status, res) => {
                    // console.log('geocoder:', res, status);
                    if(status === 'complete' && res.info === 'OK') this.createData(res.regeocode, lnglat);
                });
            });
        },
        //显示位置信息
        createData(res, lnglat){
            let data = res.addressComponent || {};
            document.querySelector('#site_coordinate').innerText = lnglat.lng + ' , ' + lnglat.lat;
            document.querySelector('#site_district').innerText = data.province + ' ' + data.city + ' ' + data.district;
            document.querySelector('#site_street').innerText = data.township;
            document.querySelector('#site_address').innerText = res.formattedAddress;
            this.result = Object.assign({}, res, {lnglat: lnglat});
        },
        fragment(template){
            return document.createRange().createContextualFragment(template);
        },
        show(e){
            let dom = document.querySelector('.site_selection');
            // console.log('event:', e);
            dom.style.top = e.clientY + 'px';
            dom.style.left = e.clientX + 'px';
            this.ele = e;
            setTimeout(() => {
                dom.classList.add('show');
            }, 150);
        },
        hide(){
            document.querySelector('.site_selection').classList.remove('show');
        }
    };

    win.Siting = Siting;
}(window);